package com.wnxy.test;

import com.wnxy.pojo.Book;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootTest
public class App2_template {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Test
    public void getBooks(){
        // 创建QueryBuilder对象
        NativeSearchQueryBuilder builder =
                new NativeSearchQueryBuilder();
        // 通过builder对象，添加查询条件
        // termQuery() 词条查询，查询条件不会分词
        // matchQuery() 分词查询，查询条件会分词
        builder.withQuery(QueryBuilders.matchQuery("bookname","Java从入门到入神"));
        // 分页 (注意：页码从0开始，0表示第1页)
        builder.withPageable(PageRequest.of(1,2));

        // 查询返回SearchHits集合，封装了查询结果
        SearchHits<Book> searchHits =
                restTemplate.search(builder.build(), Book.class);
        long totalHits = searchHits.getTotalHits();
        System.out.println("查询总记录数：" + totalHits);

        /*List<Book> list = new ArrayList<>();
        // 遍历查询结果
        for (SearchHit<Book> searchHit : searchHits) {
            Book book = searchHit.getContent();
            list.add(book);
        }
        list.forEach(System.out::println);*/

        // 通过lamda表达式一行代码优化
        List<Book> list =
                searchHits.get().map(SearchHit::getContent).collect(Collectors.toList());
        list.forEach(System.out::println);
    }
}
